<?php

	include_once("parser.php");
	//include("PostContainer.php");

	class RedditParser extends Parser {
		//TODO add parameter for subreddit
		function __construct($subreddit) {
			parent::__construct();
			if($subreddit=="") {
				$this->url = "http://www.reddit.com";
				$this->name = "RedditFront";
			}
			else {
				$this->url = "http://www.reddit.com/r/".$subreddit;
				$this->name = "Reddit".ucfirst($subreddit);
			}
		}
		
		function scrapePosts() {
			//use curl to get html of page
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $this->url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$html = curl_exec($ch);      
			curl_close($ch);
			
			//set up domxpath to query html
			$dom = new domDocument;
			@$dom->loadHTML($html);
			$dom->preserveWhiteSpace = true;
			$finder = new DomXPath($dom);
			$classname = " thing id-t3";
			
			//Use query to find specific div with content
			$table = $finder->query("//div[@id='siteTable']/div[starts-with(@class, ' thing')]");
			$nodeNum = $table->length;
			//echo $nodeNum . " Posts<br>";
			$posts = array();
			for($i=0; $i<$nodeNum; $i++) {
				$node = $table->item($i);
				$post = new Post();
				
				//get rank of post
				$post->rank = $node->childNodes->item(1)->nodeValue;
				
				//get image and url of post
				for($j=0; $j<$node->childNodes->length; $j++) {
					if($node->childNodes->item($j)->getAttribute('class') == 'thumbnail ') {
						$image = $node->childNodes->item($j)->getAttribute('href');
						if(strpos($image, "http") !== false) {
							$post->image = $image;
						}
					}
					if($node->childNodes->item($j)->getAttribute('class') == 'entry unvoted') {
						$info = $node->childNodes->item($j)->childNodes->item(0)->childNodes->item(0);
						$link = $info->getAttribute('href');
						if(strpos($link, '/r/') !== false && strpos($link, '/r/') == 0) {
							$link = 'http://reddit.com' . $link;
						}
            $post->url = $link;
						$post->content = $info->nodeValue;
					}
				}
				
				array_push($posts, $post);
			}
			
			return $posts;
		}
	}


?>